package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.pojo.PlanSafeguard;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.IPlanSafeguardService;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description：保障项服务实现类
 */
@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {


    @Autowired
    private ICategorySafeguardService categorySafeguardService;

    @Autowired
    private IPlanSafeguardService planSafeguardService;

    private LambdaQueryWrapper<Safeguard> queryMapper(SafeguardVO safeguardVO) {
        LambdaQueryWrapper<Safeguard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(safeguardVO.getSafeguardKey()), Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                    .like(StrUtil.isNotBlank(safeguardVO.getSafeguardKeyName()), Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName())
                    .eq(StrUtil.isNotBlank(safeguardVO.getDataState()), Safeguard::getDataState, safeguardVO.getDataState());
        return queryWrapper;

    }


    @Override
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        //分页查询
        Page<Safeguard> page = this.page(new Page<>(pageNum, pageSize), queryMapper(safeguardVO));
        /*Page<Safeguard> page = this.lambdaQuery()
                .eq(StrUtil.isNotBlank(safeguardVO.getSafeguardKey()), Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .like(StrUtil.isNotBlank(safeguardVO.getSafeguardKeyName()), Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName())
                .eq(StrUtil.isNotBlank(safeguardVO.getDataState()), Safeguard::getDataState, safeguardVO.getDataState())
                .page(new Page<>(pageNum, pageSize));*/
        Page<SafeguardVO> voPage = BeanConv.toPage(page, SafeguardVO.class);
        return voPage;
    }

    @Override
    public SafeguardVO findById(String safeguardId) {
        //查找对象
        Safeguard safeguard = this.getById(Long.valueOf(safeguardId));
        if (safeguard == null) {
            log.error("保障项不存在，id为：{}", safeguardId);
            throw new ProjectException(SafeguardEnum.FIND_ONE_FAIL);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class) //只要后续还有代码，就要有，因为不确定后面是否会抛异常
    public SafeguardVO save(SafeguardVO safeguardVO) {
        //新增，健壮性判段
        //判断key是否唯一
        Integer count = this.lambdaQuery().eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .eq(Safeguard::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        if (count > 0) {
            log.error("key重复，key为：{}", safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
        Safeguard bean = BeanConv.toBean(safeguardVO, Safeguard.class);
        this.save(bean);
        return BeanConv.toBean(bean, SafeguardVO.class);
    }

    @Override
    @Transactional
    public Boolean update(SafeguardVO safeguardVO) {
        //健壮性判断
        Safeguard safeguard = this.getById(safeguardVO.getId());
        if (safeguard == null) {
            log.error("保障项为空，key为：{}", safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //判断修改后的key是否唯一,这算一个筛选条件
        Integer count = this.lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .ne(Safeguard::getId, safeguardVO.getId())
                .count();
        if (count > 0) {
            log.error("保障项的key已存在，key为：{}", safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //判断是否冗余字段，即是否被其他表关联，数据在多个表中存在
        //处理的两种方法，  1.全部都修改   2.有关联，不让修改
        Integer count1 = categorySafeguardService.lambdaQuery()
                .eq(CategorySafeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        Integer count2 = planSafeguardService.lambdaQuery()
                .eq(PlanSafeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        if (count1 > 0 || count2 > 0) {
            log.error("保障项被关联，不能修改，key为：{}", safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        boolean result = this.updateById(BeanConv.toBean(safeguardVO, Safeguard.class));
        return result;
    }

    //批量删除，第一种，关联的不删除，不关联的删除，由于提示不友好，不适用
    //批量删除2，只要有关两，批量删除全部不成功
    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //方法1
        /*if(checkedIds.length==0){
            log.error("没有要删除的数据");
            return true;
        }
        //List<Long> ids = Arrays.asList(checkedIds).stream().map(id -> Long.valueOf(id)).collect(Collectors.toList());
        List<String> ids = Arrays.asList(checkedIds);
        for (int i = 0; i < ids.size(); i++) {
            String id = ids.get(i);
            Safeguard safeguard = this.getById(id);
            if(safeguard==null){
                log.error("不存在该保障项,id为：{}",id);
                ids.remove(i);
                continue;
            }
            //判断是否冗余字段，即是否被其他表关联，数据在多个表中存在
            //处理的两种方法，  1.全部都修改   2.有关联，不让修改
            Integer count1 = categorySafeguardService.lambdaQuery()
                    .eq(CategorySafeguard::getSafeguardKey, safeguard.getSafeguardKey())
                    .count();
            Integer count2 = planSafeguardService.lambdaQuery()
                    .eq(PlanSafeguard::getSafeguardKey, safeguard.getSafeguardKey())
                    .count();
            if(count1>0  || count2>0){
                log.error("保障项被关联，不能删除，key为：{}",safeguard.getSafeguardKey());
                ids.remove(i);
            }
        }
        if(CollUtil.isEmpty(ids)){
            log.error("没有要删除的数据");
            return true;
        }
        //剩余要删除的ids集合
        boolean result = this.removeByIds(ids);
        return result;*/

        //方法2
        /*if(checkedIds.length==0){
            log.error("没有要删除的数据");
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
        //List<Long> ids = Arrays.asList(checkedIds).stream().map(id -> Long.valueOf(id)).collect(Collectors.toList());
        List<String> ids = Arrays.asList(checkedIds);
        for (int i = 0; i < ids.size(); i++) {
            String id = ids.get(i);
            Safeguard safeguard = this.getById(id);
            if(safeguard==null){
                log.error("不存在该保障项,id为：{}",id);
                throw new ProjectException(SafeguardEnum.DEL_FAIL);
            }
            //判断是否冗余字段，即是否被其他表关联，数据在多个表中存在
            //处理的两种方法，  1.全部都修改   2.有关联，不让修改
            Integer count1 = categorySafeguardService.lambdaQuery()
                    .eq(CategorySafeguard::getSafeguardKey, safeguard.getSafeguardKey())
                    .count();
            Integer count2 = planSafeguardService.lambdaQuery()
                    .eq(PlanSafeguard::getSafeguardKey, safeguard.getSafeguardKey())
                    .count();
            if(count1>0  || count2>0){
                log.error("存在保障项被关联，不能删除，key为：{}",safeguard.getSafeguardKey());
                throw new ProjectException(SafeguardEnum.DEL_FAIL);
            }
        }
        //剩余要删除的ids集合
        //全部不被关联才可以被删除
        return this.removeByIds(ids);*/
        //方法3
        //讲义方法
        List<String> ids = Arrays.asList(checkedIds);
        //先把保障项查出来
        List<Safeguard> safeguards = this.listByIds(ids);
        if (CollUtil.isEmpty(safeguards)) {
            log.info("保障项不存在，ids：{}", ids);
            return true;
        }
        Set<String> keys = safeguards.stream().map(Safeguard::getSafeguardKey).collect(Collectors.toSet());
        Integer count1 = categorySafeguardService.lambdaQuery()
                .in(CategorySafeguard::getSafeguardKey, keys)
                .count();
        Integer count2 = planSafeguardService.lambdaQuery()
                .in(PlanSafeguard::getSafeguardKey, keys)
                .count();
        if (count1 > 0 || count2 > 0) {
            log.error("存在保障项被关联，不能删除，keys为：{}", keys);
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
        return this.removeByIds(ids);
    }

    @Override
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        //查询集合
        List<Safeguard> list = this.list(queryMapper(safeguardVO));
        if(list==null){
            log.error("不存在保障项集合");
            throw new ProjectException(SafeguardEnum.LIST_FAIL);
        }
        return BeanConv.toBeanList(list,SafeguardVO.class);
    }


    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        //TODO
        return null;
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        //TODO
        return null;
    }
}
